package com.yangchao.ch04

class exmpale4 {
    public static void main(String[] args) {
        def student=new Student()
        def worker=new Worker()
        student.showParter() //生物系
        //通过元对象类修改私有属性，不推荐
        Student.metaClass.setAttribute(student,"parter","经济系")
        student.showParter() //经济系

        worker.id=1000
        worker.name="李其"
        println("Worker id=${worker.id}name=${worker.name}")

    }
}

class Student{
    private String parter="生物系"

    def showParter(){
        println("Student:"+this.parter)
    }
}


// 实现了元对象接口
class Worker implements GroovyInterceptable {

    private String parter = "运输部"

    // 存储运行时动态添加的属性  空Map
    private dynamicProps = [:]

    def getParter() {
        this.parter
    }

    void setProperty(String varName, Object value) {
        this.dynamicProps[varName] = value
    }

    Object getProperty(String varName) {
        this.dynamicProps[varName]
    }

    // 执行任何方法的时候，都会调用
    Object invokeMethod(String methodName, Object args) {
        def metaMethod = Worker.metaClass.getMetaMethod(methodName, args)
        if (metaMethod) {
            return metaMethod.invoke(this, args)
        }
        return "Missing Method name=${methodName} args=${args}"
    }

    MetaClass getMetaClass() {}

    void setMetaClass(MetaClass var1) {}
}

